package com.pruebas.physics.rotatingcube;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.pruebas.physics.common.Cube;
import com.pruebas.physics.common.SurfaceMapper;


import android.opengl.GLSurfaceView;
import android.opengl.GLU;

public class RotatingCubeRenderer implements GLSurfaceView.Renderer {
	private SurfaceMapper surfaceMapper;
	
	private Cube cube;
	
	private float cubeLastSpeed = 0f;
	/*private float cubeLastXPos = 0f;
	private float cubeLastYPos = 0f;
	private float cubeLastZPos = 0f;*/
	
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// Set the background frame color
        gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        // initialize the rectangle vertex array
        initShapes();
        // Enable use of vertex arrays
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    }
    
    public void onDrawFrame(GL10 gl) {
    	// Redraw background color
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        
        this.cubeLastSpeed += 2;
        
        //world
        gl.glPushMatrix();
        gl.glColor4f(0f, 1f, 1f, 0.0f);
        gl.glRotatef(this.cubeLastSpeed, 1f, 1f, 1f);
        cube.draw(gl);
        gl.glPopMatrix();
    }
    
    public void onSurfaceChanged(GL10 gl, int width, int height) {
    	this.surfaceMapper = new SurfaceMapper(width, height, 5f);
    	
        gl.glViewport(0, 0, width, height);
        
        // make adjustments for screen ratio
        gl.glMatrixMode(GL10.GL_PROJECTION);        // set matrix to projection mode
        gl.glLoadIdentity();                        // reset the matrix to its default state
        gl.glFrustumf(-this.surfaceMapper.getRatio(), this.surfaceMapper.getRatio(), -1, 1, 1f, 10);  // apply the projection matrix
        
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        // Set GL_MODELVIEW transformation mode
        GLU.gluOrtho2D(gl,
        		-this.surfaceMapper.getMagicX(), this.surfaceMapper.getMagicX(),
        		-this.surfaceMapper.getMagicY(), this.surfaceMapper.getMagicY());
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity(); // reset the matrix to its default state
        // When using GL_MODELVIEW, you must set the view point
        GLU.gluLookAt(gl, 0, 0, -1f, 0f, 0f, 0f, 0f, 1f, 0.0f);

    }
    
    private void initShapes(){
    	this.cube = new Cube(2f);
    }    
}